//
//  GCD+timer.swift
//  HXPPApp_iOS
//
//  Created by hxpp on 2018/7/19.
//  Copyright © 2018年 HXPP technology co., LTD. All rights reserved.
//

import Foundation
import UIKit


/// GCD定时器循环操作
///   - timeInterval: 循环间隔时间
///   - handler: 循环事件
public func DispatchTimer(timeInterval: Double, handler:@escaping (DispatchSourceTimer?)->())
{
    let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
    timer.schedule(deadline: .now(), repeating: timeInterval)
    timer.setEventHandler {
        DispatchQueue.main.async {
            handler(timer)
        }
    }
    timer.resume()
}

/// GCD延时操作
///   - after: 延迟的时间
///   - handler: 事件
public func DispatchAfter(after: Double, handler:@escaping ()->())
{
    DispatchQueue.main.asyncAfter(deadline: .now() + after) {
        handler()
    }
}

public func scheduledDispatchTimer(total : Int, handler : ((_ total : Int)->())?, cancelHandler : (()->Void)?, sender : UIView?) {

    var total = total
    
    let gcdTimer = DispatchSource.makeTimerSource()

    gcdTimer.schedule(wallDeadline: DispatchWallTime.now(), repeating: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.seconds(0))
    
    weak var v = sender
    
    gcdTimer.setEventHandler {
        if v == nil {
            gcdTimer.cancel()
        }
        
        DispatchQueue.main.async {
            handler?(total)
            DDump(obj: total)
            if total == 0 {
                cancelHandler?()
                gcdTimer.cancel()
            }else {
                total -= 1
            }
        }
    }

    gcdTimer.resume()
    
}
